package org.gl.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Dateutil {
	// 定义模板将取出来的日期转换成指定格式
	public final static SimpleDateFormat SimpleDateFormat__YYYYMMDDHHMMSS = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	public final static SimpleDateFormat SimpleDateFormat__YYYYMMDD = new SimpleDateFormat(
			"yyyy-MM-dd");

	/**
	 * 默认返回当前时间的 年月日时分秒毫秒
	 * 
	 * @param sdf
	 * @return
	 */
	public static String getTimeString(SimpleDateFormat sdf, long mtime) {
		if (mtime <= 0) {
			mtime = System.currentTimeMillis();
		}
		if (sdf == null) {
			return SimpleDateFormat__YYYYMMDDHHMMSS.format(new Date(mtime));
		}
		return sdf.format(new Date(mtime));

	};

	/**
	 * 得到当前时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
	 */
	public static String getNextDayString(int delay) {
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String mdate = "";
			Date d = new Date(System.currentTimeMillis());
			long myTime = (d.getTime() / 1000) + delay * 24 * 60 * 60;
			d.setTime(myTime * 1000);
			mdate = format.format(d);
			return mdate;
		} catch (Exception e) {
			return "";
		}
	}
	/**
	 * 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
	 */
	public static String getNextDayString(String fromtDataString,int delay) {
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String mdate = "";
			Date d = new Date(convert2long(fromtDataString,"yyyy-MM-dd"));
			long myTime = (d.getTime() / 1000) + delay * 24 * 60 * 60;
			d.setTime(myTime * 1000);
			mdate = format.format(d);
			return mdate;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 毫秒转时分秒字符串
	 * 
	 * @return
	 */
	public static String milliSecendToHMSString(long milliSecend) {
		long totalSecond = milliSecend / 1000;
		long second = 0;
		long minute = 0;
		long hours = 0;
		long temp = totalSecond / 60;
		long temp2 = temp / 60;
		if (temp >= 60) {
			hours = temp2 % 60;
		}
		if (totalSecond >= 60) {
			minute = temp % 60;
		}
		second = totalSecond % 60;
		StringBuilder sb = new StringBuilder();
		sb.append(hours > 9 ? hours : "0" + hours);
		sb.append(":");
		sb.append(minute > 9 ? minute : "0" + minute);
		sb.append(":");
		sb.append(second > 9 ? second : "0" + second);
		return sb.toString();
	}

	/**
	 * 将日期格式的字符串转换为长整型
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static long convert2long(String date, String format) {
		try {
			if (date != null && date.length() > 0) {
				SimpleDateFormat sf;
				if (format == null || format.length() <= 0) {
					sf = SimpleDateFormat__YYYYMMDD;
				}else{
					sf = new SimpleDateFormat(format);
				}
				return sf.parse(date).getTime();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0L;
	}
}
